package dimension.starry.block.machine.industry.rollingMill;

import dimension.starry.StarryDimension;
import dimension.starry.block.machine.industry.IndustryMachineRegister;
import dimension.starry.block.machine.simple.castTable.CastTableContainer;
import dimension.starry.block.typeInterface.MachineTileEntity;
import dimension.starry.item.ItemRegisterManager;
import net.minecraft.block.BlockState;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.screen.ScreenHandler;
import net.minecraft.text.Text;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;

/**
 * @author 150149
 */
public class RollingMillTileEntity extends MachineTileEntity {

    private static final Text TITLE = Text.translatable("block." + StarryDimension.MOD_ID + ".rolling_mill");

    public RollingMillTileEntity(BlockPos pos, BlockState state) {
        super(IndustryMachineRegister.ROLLING_MILL.getBlockEntityType(), pos, state, 2, TITLE, 800);
    }

    private static Item getOutput(ItemStack input) {
        Item item = input.getItem();
        if (ItemRegisterManager.STEEL.getItem().equals(item)) {
            return ItemRegisterManager.STEEL_PLATE.getItem();
        }
        return null;
    }

    @Override
    public ScreenHandler createMenu(int sycID, PlayerInventory inventory, PlayerEntity player) {
        return new RollingMillContainer(
            IndustryMachineRegister.ROLLING_MILL.getScreenHandlerType(), sycID, inventory, getPos());
    }

    @Override
    public void tick(
        World world, BlockPos pos, BlockState state1, MachineTileEntity blockEntity
    ) {
        if (world == null || world.isClient() || !this.hasSteam()) {
            return;
        }

        ItemStack ingotStack = this.inventory.getStack(0);

        if (ingotStack.isEmpty()) {
            this.setMachineStatus(false);
            this.resetProgress();
        } else if (getOutput(ingotStack) == null) {
            this.setMachineStatus(false);
            this.resetProgress();
        } else if (this.getProgress() >= this.getConsumeTime()) {
            ItemStack itemStack = new ItemStack(getOutput(ingotStack));
            if (this.inventory.canInsert(itemStack)) {
                ingotStack.setCount(ingotStack.getCount() - 1);
                this.resetProgress();
                this.inventory.addStack(itemStack);
            }
        } else {
            this.addProgress();
        }
    }

}
